package com.heima.wemedia.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.excpetion.CustException;
import com.heima.file.service.FileStorageService;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.WmThreadLocalUtils;
import com.heima.model.wemedia.dtos.WmMaterialDTO;
import com.heima.model.wemedia.pojos.WmMaterial;
import com.heima.model.wemedia.pojos.WmNewsMaterial;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.wemedia.mapper.WmMaterialMapper;
import com.heima.wemedia.mapper.WmNewsMaterialMapper;
import com.heima.wemedia.service.WmMaterialService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.*;

@Service("WmMaterialService")
public class WmMaterialServiceImpl extends ServiceImpl<WmMaterialMapper, WmMaterial> implements WmMaterialService {

    @Value("${file.oss.web-site}")
    private String webSite;

    @Value("${file.oss.prefix}")
    String prefix;

    @Autowired
    FileStorageService fileStorageService;

    @Autowired
    WmNewsMaterialMapper wmNewsMaterialMapper;


    /**
     * 上传图片
     *
     * @param multipartFile
     * @return
     */
    @Override
    public ResponseResult upload(MultipartFile multipartFile) {
        //判断上传文件 底层默认最大上传大小为1MB
        if (multipartFile == null || multipartFile.getSize() == 0)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);

        //检查线程中是否有User 否返回
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        ArrayList<String> list = new ArrayList<>();
        list.add(".jpg");
        list.add(".png");
        list.add(".gif");
        list.add(".jpeg");

        String filename = multipartFile.getOriginalFilename();


        if (filename == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);

        if (!checkFileSuffix(filename)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "请上传正确的素材格式,[jpg,jpeg,png,gif]");
        }

        //生成一个随机的字符串
        String randomFileName = UUID.randomUUID().toString().replace("-", "");

        //拼接成一个新文件名
        String contentType = filename.substring(filename.lastIndexOf("."));


        String fileId = null;
        try {
            fileId = fileStorageService.store(prefix, randomFileName + contentType, multipartFile.getInputStream());
        } catch (IOException e) {
            e.printStackTrace();
        }


        //  封装数据并保存到素材库中
        WmMaterial wmMaterial = new WmMaterial();
        wmMaterial.setIsCollection((short) 0);
        wmMaterial.setType((short) 0);
        wmMaterial.setCreatedTime(new Date());
        // 设置文件id
        wmMaterial.setUrl(fileId);
        wmMaterial.setUserId(user.getId());
        //执行保存操作
        super.save(wmMaterial);
        // 前端显示
        wmMaterial.setUrl(webSite + fileId);
        // 4 返回结果
        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 显示素材列表
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult findList(WmMaterialDTO dto) {
        if (dto == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_REQUIRE);
        //检查参数
        dto.checkParam();

        LambdaQueryWrapper<WmMaterial> lambdaQuery = Wrappers.lambdaQuery();

        //如果用户收藏则添加收藏条件
        if (dto.getIsCollection() != null && dto.getIsCollection() == 1)
            lambdaQuery.eq(WmMaterial::getIsCollection, dto.getIsCollection());

        //根据收藏时间倒叙排序
        lambdaQuery.orderByDesc(WmMaterial::getCreatedTime);

        // 执行查询
        Page<WmMaterial> page = new Page<>(dto.getPage(), dto.getSize());
        IPage<WmMaterial> materialIPage = super.page(page, lambdaQuery);

        //取出查询结果集
        List<WmMaterial> records = materialIPage.getRecords();

        // 批量设置素材的真实地址
        for (WmMaterial record : records) {
            record.setUrl(webSite + record.getUrl());
        }

        return new PageResponseResult(dto.getPage(), dto.getSize(), materialIPage.getTotal(), records);
    }

    /**
     * 删除图片
     *
     * @param id
     * @return
     */
    @Transactional
    @Override
    public ResponseResult delPicture(Integer id) {
        if (id == null)
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);

        // 从线程中取出用户对象
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        // 根据Id查询数据库中对应的素材信息 无->返回错误
        WmMaterial material = super.getById(id);
        if (material == null)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);

        //判断素材是否被引用
        LambdaQueryWrapper<WmNewsMaterial> lambdaQuery = Wrappers.lambdaQuery();
        lambdaQuery.eq(WmNewsMaterial::getMaterialId, id);
        //查询被引用的数量
        Integer selectCount = wmNewsMaterialMapper.selectCount(lambdaQuery);
        if (selectCount > 0)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW);

        // 删除数据库中保存的素材信息
        super.removeById(id);

        // 删除oss中的图片信息
        fileStorageService.delete(material.getUrl());

        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 收藏与取消图片
     *
     * @param id
     * @param cancelCollectMaterial
     * @return
     */
    @Transactional
    @Override
    public ResponseResult updateStatus(Integer id, Short cancelCollectMaterial) {

        if (id == null || cancelCollectMaterial == null)
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID);

        WmMaterial wmMaterial = super.getById(id);

        //判断是否找到目标素材
        if (wmMaterial == null)
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST);

        // 从线程中取出用户对象
        WmUser user = WmThreadLocalUtils.getUser();
        if (user == null)
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);

        // 比较收藏列表的用户和当前线程中的用户是否同一个
        if (!user.getId().equals(wmMaterial.getUserId()))
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "只允许收藏自己上传的素材");


        //设置目标状态值
        wmMaterial.setIsCollection(cancelCollectMaterial);

        //执行修改
        super.update(Wrappers.<WmMaterial>lambdaUpdate()
                .set(WmMaterial::getIsCollection, cancelCollectMaterial)
                .eq(WmMaterial::getId, id)
                .eq(WmMaterial::getUserId, wmMaterial.getUserId()));


        return ResponseResult.okResult(wmMaterial);
    }

    /**
     * 检查文件格式 目前仅仅支持jpg  jpeg  png  gif 图片的上传
     *
     * @param path
     * @return
     */
    private boolean checkFileSuffix(String path) {
        if (StringUtils.isBlank(path)) return false;
        List<String> allowSuffix = Arrays.asList("jpg", "jpeg", "png", "gif");
        boolean isAllow = false;
        for (String suffix : allowSuffix) {
            if (path.endsWith(suffix)) {
                isAllow = true;
                break;
            }
        }
        return isAllow;
    }
}
